﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Cqrs.Common;

namespace Cqrs.Common
{
    public class CommandEvent
    {
        public string Command { get; set; }
        public string Event { get; set; }
        public List<DomainProperty> AffectedProperties { get; set; }

        public static List<CommandEvent> ConvertXElementsToCommandEvent(
            IEnumerable<XElement> commandEventXmlElements)
        {
            List<CommandEvent> commandEvents = new List<CommandEvent>();
            foreach (XElement commandEventElement in commandEventXmlElements)
            {
                CommandEvent commandEvent = new CommandEvent()
                {
                    Command = commandEventElement.Name.LocalName,
                    Event = commandEventElement.Attribute("Event").Value,
                    AffectedProperties = new List<DomainProperty>()
                };
                foreach (XElement property in commandEventElement.Elements())
                {
                    commandEvent.AffectedProperties.Add(
                        new DomainProperty()
                        {
                            Name = property.Name.LocalName,
                            Type = property.Attribute("Type").Value
                        });
                }
                commandEvents.Add(commandEvent);
            }
            return commandEvents;
        }

        public static XElement ConvertCommandEventToXElement(IEnumerable<CommandEvent> commandEvents)
        {
            XElement xelement = new XElement("AdHocMethods");
            foreach (CommandEvent commandEvent in commandEvents)
            {
                XElement commandEventElement = new XElement(commandEvent.Command);
                commandEventElement.Add(new XAttribute("Event", commandEvent.Event));

                foreach (DomainProperty property in commandEvent.AffectedProperties)
                {
                    XElement propertyElement = new XElement(property.Name);
                    propertyElement.Add(new XAttribute("Type", property.Type));
                    commandEventElement.Add(propertyElement);
                }
                xelement.Add(commandEventElement);
            }
            return xelement;
        }
    }
}
